package com.fastloan.mgt.product.basics.service.impl;

import com.fastloan.common.BasicServiceImpl;
import com.fastloan.mgt.product.basics.dao.ProductTempMapper;
import com.fastloan.mgt.product.basics.model.Product;
import com.fastloan.mgt.product.basics.model.ProductTemp;
import com.fastloan.mgt.product.basics.service.ProductService;
import com.fastloan.mgt.product.basics.service.ProductTempService;
import com.fastloan.mgt.product.temp.model.DefTemp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Optional;

import static com.fastloan.mgt.product.enums.ProductEnum.PUBLISHED;
import static com.fastloan.mgt.product.enums.ProductEnum.UNPUBLISHED;
import static java.util.stream.Collectors.toList;

/**
 * @author admins
 *         createTime 2017/11/07
 */
@Service
public class ProductTempServiceImpl extends BasicServiceImpl<ProductTemp> implements ProductTempService {
    @Autowired
    private ProductTempMapper productTempMapper;

    @Autowired
    private ProductService productService;

    @Override
    @Transactional
    public Integer pageParameter(List<ProductTemp> productTempList) {
        Optional<ProductTemp> optional = productTempList
                .stream()
                .filter(productTemp -> productTemp.getType() != null)
                .findAny();
        if (optional.isPresent()) {
            ProductTemp temp = optional.get();
            String productId = temp.getProductId();
            Product product = productService.selectByPrimaryKey(productId);
            //非创建中的产品
            ProductTemp productTemp = new ProductTemp();
            productTemp.setProductId(productId);
            productTemp.setStatus(UNPUBLISHED.getType());
            productTemp.setType(temp.getType());
            if (!product.getStatus().equals(UNPUBLISHED.getType())) {
                List<ProductTemp> tempList = select(productTemp);
                tempList.forEach(productTemp1 -> {
                    productTemp1.setStatus(PUBLISHED.getType());
                    updateByPrimaryKeySelective(productTemp1);
                });
            }
            delete(productTemp);
            return productTempMapper.insertList(productTempList);
        }
        throw new RuntimeException("错误的ipc格式");
    }

    @Override
    public Integer tempCount(String productId) {
        Example example = new Example(ProductTemp.class);
        example.createCriteria().andEqualTo("productId", productId)
                .andEqualTo("status", UNPUBLISHED.getType());
        return selectCountByExample(example);
    }
}
